package com.example.filter;

import com.example.util.JwtTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.example.util.JwtTokenUtil.TOKEN_HEADER;

/**
 * 自定义全局过滤器
 */
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    private static  final Logger LOG  = LoggerFactory.getLogger(CustomGlobalFilter.class);
    // 根据实际项目，再做配置
    private static  final  String KEY ="huanaikey";
    /**
     * 过滤器业务逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        LOG.info("进入全局过滤器！");
        //1. 获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2. 则获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3. 如果是登录请求则放行
        if (request.getURI().getPath().contains("/login")) {
            LOG.info("登录操作！");
            return chain.filter(exchange);
        }
        //插入内部（待确定）
        String key = exchange.getRequest().getQueryParams().getFirst("SecretKey");
        LOG.info(key);
        if (KEY.equals(key)){
            LOG.info("内部调用！");
            return chain.filter(exchange);
        }
        //4. 获取请求头
        HttpHeaders headers = request.getHeaders();
        //5. 请求头中获取令牌
        String token = headers.getFirst(TOKEN_HEADER);

        //6. 判断请求头中是否有令牌
        if (StringUtils.isEmpty(token)) {
            response.getHeaders().add("Content-Tpye","application/json; charset=utf-8");
            //7. 响应中放入返回的状态吗, 没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String message = "{\"message\":\""+HttpStatus.UNAUTHORIZED.getReasonPhrase()+"\"}";
            DataBuffer buffer = response.bufferFactory().wrap(message.getBytes());
            //8. 返回
            return response.writeWith(Mono.just(buffer));
        }


        //9. 如果请求头中有令牌则解析令牌
        try {
            JwtTokenUtil.checkJWT(token);
            System.out.println("token正确！");
        } catch (Exception e) {
            e.printStackTrace();
            //10. 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
            DataBuffer buffer = response.bufferFactory().wrap(e.getMessage().getBytes());
            //11. 返回
            return response.writeWith(Mono.just(buffer));

        }
        System.out.println("自定义全局过滤器被执行");
        return chain.filter(exchange); // 继续向下执行
    }

    /**
     * 过滤器执行顺序，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

}
